from tsvetaeva.thesaurus.models import *
from django.contrib import admin

import re

class ParserAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        try:
            text = obj.comment
        except AttributeError:
            text = obj.text
        m = re.finditer(r'\(person\)\[(?P<text>.*?)\](?:\[(?P<link>.*?)\])?', text)
        persons = []
        for match in m:
            if match.group("link"):
                link = match.group("link")
            else:
                link = match.group("text")
            persons.append(link)
        persons = list(set(persons))
        for person in persons:
            p,created = Person.objects.get_or_create(name=person)
            obj.persons.add(p)
        obj.save()

admin.site.register(Taxon)
admin.site.register(Work, ParserAdmin)
admin.site.register(Word)
admin.site.register(WordMeaning)
admin.site.register(UsageType)
admin.site.register(Usage, ParserAdmin)
admin.site.register(Person)
